package com.zeny.edu.ucenter.api;

import com.alibaba.fastjson.JSON;
import com.zeny.edu.common.CookieUtil;
import com.zeny.edu.ucenter.entity.Member;
import com.zeny.edu.ucenter.service.MemberService;
import com.zeny.edu.ucenter.util.ConstantPropertiesUtil;
import com.zeny.edu.ucenter.util.HttpclientUtil;
import com.zeny.edu.ucenter.util.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName WxApiController
 * @Description TODO
 * @Author zeny
 * @Date 2020/3/11 0011 11:16
 */
@Controller
@RequestMapping("/api/ucenter/wb")
@CrossOrigin
public class WbApiController {

    @Autowired
    private MemberService memberService;

    @GetMapping("/login/{vb}")
    public String genQrConnect(@PathVariable String vb) {
        String url = "";
        if ("weibo".equals(vb)) {
            url = "https://api.weibo.com/oauth2/authorize?client_id="+ConstantPropertiesUtil.WX_OPEN_APP_ID+"&response_type=code&redirect_uri="+ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        }else if ("bendi".equals(vb)){

        }
      return "redirect:" + url;
    }

    @RequestMapping("/vlogin")
    public String vlogin(String code, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //授权码换取access_token,code是授权后回调地址带回的，就是response_type=code
        //https://api.weibo.com/oauth2/authorize?client_id=1288161722&response_type=code&redirect_uri=http://127.0.0.1:8085/api/ucenter/wb/vlogin
        String access_token = getAccess_token(code);
        //access_token换区用户信息
        Map<String, Object> userMap = new HashMap<>();
        String uid = "";
        String accessTokenStr = "";
        if (StringUtils.isNotBlank(access_token)) {
            //access_token是json串，实际的access_token在里面，取出来就是accessTokenStr，uid也在json串里面
            Map<String, Object> accessMap = JSON.parseObject(access_token, Map.class);
            accessTokenStr = (String) accessMap.get("access_token");
            uid = (String) accessMap.get("uid");
            String access_token_get_msg_url = "https://api.weibo.com/2/users/show.json?access_token=" + accessTokenStr + "&uid=" + uid;
            String userMsg = HttpclientUtil.doGet(access_token_get_msg_url);
            //用户信息
            userMap = JSON.parseObject(userMsg, Map.class);
        } else {
            //access_token为空，回到登录页面
            return "redirect:/index";
        }
        //将用户信息userMap保存数据库，用户类型设置为微博用户
        String nickname = (String) userMap.get("name");
        String avatar = (String) userMap.get("avatar_large");
        String openId = (String) userMap.get("idstr");
        Integer sex = userMap.get("gender").equals("m")? 2 : 1;

        Member member = new Member();
        member.setAvatar(avatar);
        member.setNickname(nickname);
        member.setOpenid(openId);
        member.setSex(sex);
        Member memberFrom = memberService.insertWeiboUser(member);
        String token = JwtUtils.genJsonWebToken(memberFrom);
        CookieUtil.setCookie(request, response,"token", token, 60*5, true);
        //生成jwt的token，并重定向到XXX页面，同时携带该token
        //我这里重定向到首页，一般来说是返回到上个页面
        return "redirect:http://localhost:3000?token=" + token;
    }

    private String getAccess_token(String code) throws Exception {
        String url = "https://api.weibo.com/oauth2/access_token?";          //下面两张图片中可以看到
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("client_id", ConstantPropertiesUtil.WX_OPEN_APP_ID);                           //上面有提到
        paramMap.put("client_secret", ConstantPropertiesUtil.WX_OPEN_APP_SECRET);                       //上面有提到
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("redirect_uri", ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL);  //回调地址
        paramMap.put("code", code);
        String access_token = HttpclientUtil.doPost(url, paramMap);
        return access_token;
    }


}
